<template>
  <div class="hotel-reviews">
    <div class="section-header">
      <comment-outlined class="section-icon" />
      <h2>用户点评</h2>
    </div>

    <!-- Review Summary -->
    <div class="review-summary">
      <div class="rating-overview">
        <div class="average-rating">
          <h2 class="rating-number">{{ reviewStats.averageRating.toFixed(1) }}</h2>
          <a-rate :value="reviewStats.averageRating" disabled allow-half />
          <p>{{ reviewStats.totalReviews }}条点评</p>
        </div>
        <div class="rating-distribution">
          <div v-for="(count, rating) in reviewStats.ratingDistribution" :key="rating" class="rating-bar">
            <span>{{ rating }}星</span>
            <a-progress 
              :percent="(count / (reviewStats.totalReviews || 1) * 100)" 
              :show-info="false"
              :stroke-color="getRatingColor(Number(rating))"
              :stroke-width="12"
            />
            <span>{{ count }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和排序控件 -->
    <div class="filter-sort-container">
      <div class="filter-container">
        <span class="filter-label">筛选: </span>
        <a-radio-group v-model:value="filterValue" button-style="solid" @change="handleFilterChange">
          <a-radio-button value="all">全部评价</a-radio-button>
          <a-radio-button value="withImages">有图评价</a-radio-button>
          <a-radio-button value="withReply">有回复</a-radio-button>
        </a-radio-group>
      </div>
      <div class="sort-container">
        <span class="sort-label">排序: </span>
        <a-select 
          v-model:value="sortValue" 
          style="width: 140px" 
          @change="handleSortChange"
        >
          <a-select-option value="newest">最新优先</a-select-option>
          <a-select-option value="highest">好评优先</a-select-option>
          <a-select-option value="lowest">差评优先</a-select-option>
        </a-select>
      </div>
    </div>

    <!-- Add Review Button -->
    <div class="add-review-section">
      <a-button type="primary" @click="goToOrderPage" size="large">
        <edit-outlined />写点评
      </a-button>
    </div>

    <!-- Review List -->
    <div class="review-list">
      <a-list
        :data-source="filteredReviews"
        :loading="loading"
        item-layout="vertical"
        :pagination="pagination"
      >
        <template #renderItem="{item}">
          <a-list-item class="review-item">
            <a-list-item-meta>
              <template #avatar>
                <a-avatar :src="item.userAvatar || getRandomAvatar(item.id)" :size="48" />
              </template>
              <template #title>
                <div class="review-header">
                  <span class="author-name">{{ item.author || '匿名用户' }}</span>
                  <a-rate :value="item.rating" disabled />
                </div>
              </template>
              <template #description>
                <span class="review-meta">{{ formatDate(item.date) }} · {{ item.roomType || '标准房' }}</span>
                <span v-if="item.tags && item.tags.length > 0" class="review-tags">
                  <a-tag v-for="tag in item.tags" :key="tag" color="blue">{{ tag }}</a-tag>
                </span>
              </template>
            </a-list-item-meta>
            
            <!-- 评论内容 -->
            <div class="review-content">{{ item.content }}</div>
            
            <!-- 评论图片 -->
            <div v-if="item.photos && item.photos.length > 0" class="review-images">
              <div 
                v-for="(image, index) in item.photos" 
                :key="index" 
                class="review-image-wrapper"
                @click="previewImage(image)"
              >
                <img :src="image" class="review-image" :alt="`评论图片${index + 1}`" />
              </div>
            </div>
            
            <!-- 酒店回复 -->
            <div v-if="item.reply" class="hotel-reply">
              <div class="reply-header">
                <crown-outlined class="reply-icon" />
                <span class="reply-title">酒店回复</span>
                <span class="reply-time">{{ formatDate(item.replyDate) }}</span>
              </div>
              <div class="reply-content">{{ item.reply }}</div>
            </div>
          </a-list-item>
        </template>
        <template #empty>
          <div class="empty-reviews">
            <a-empty description="暂无评价" />
          </div>
        </template>
      </a-list>
    </div>

    <!-- 图片预览 -->
    <a-image-preview-group>
      <a-image
        v-for="(url, index) in previewImages"
        :key="index"
        :src="url"
        style="display: none;"
      />
    </a-image-preview-group>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { EditOutlined, CommentOutlined, CrownOutlined } from '@ant-design/icons-vue'
import { apiGetHotelReviews, apiGetHotelReviewStats } from '@/api/api'
import { useHotelDetailStore } from '@/stores/hotelDetailStrore'
import type { HotelReview } from '@/stores/hotelDetailStrore'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { Result } from '@/types'

// 统计信息接口
interface ReviewStats {
  totalReviews: number;
  averageRating: number;
  ratingDistribution: {
    [key: string]: number;
  };
}

// 扩展HotelReview接口以包含可能的后端字段
interface ExtendedReviewData {
  id: number;
  userName?: string;
  username?: string;
  userAvatar?: string;
  avatar?: string;
  content: string;
  rating: number;
  date?: string;
  createTime?: string;
  roomType?: string;
  images?: string | string[];
  photos?: string[];
  tags?: string[];
  reply?: string;
  replyDate?: string;
  replyTime?: string;
  status?: string;
  [key: string]: any; // 允许其他可能的字段
}

// 扩展HotelReview接口
interface EnhancedHotelReview extends HotelReview {
  userName?: string;
  userAvatar?: string;
  photos?: string[];
  tags?: string[];
  reply?: string;
  replyDate?: string;
  status?: string;
}

interface ReviewResponse {
  code: number;
  msg?: string;
  data?: {
    records?: ExtendedReviewData[];
    total?: number;
    pages?: number;
    current?: number;
    size?: number;
  };
}

const props = defineProps<{
  hotelId: string | number
}>()

const router = useRouter()
const hotelDetailStore = useHotelDetailStore()
const { hotelDetail, loading: storeLoading } = storeToRefs(hotelDetailStore)

const loading = ref(false)
const reviews = ref<EnhancedHotelReview[]>([])
const reviewModalVisible = ref(false)
const submitting = ref(false)

// 统计信息
const reviewStats = reactive<ReviewStats>({
  totalReviews: 0,
  averageRating: 0,
  ratingDistribution: {
    "5": 0,
    "4": 0,
    "3": 0,
    "2": 0,
    "1": 0
  }
})

// 筛选和排序
const filterValue = ref('all')
const sortValue = ref('newest')

// 图片预览相关
const previewVisible = ref(false)
const previewImages = ref<string[]>([])
const activePreviewIndex = ref(0)

// 分页相关
const pagination = reactive({
  current: 1,
  pageSize: 5,
  total: 0,
  onChange: (page: number) => {
    pagination.current = page
    loadReviews(page)
  }
})

// 筛选后的评论
const filteredReviews = computed(() => {
  let result = [...reviews.value]
  
  // 应用筛选
  if (filterValue.value === 'withImages') {
    result = result.filter(review => review.photos && review.photos.length > 0)
  } else if (filterValue.value === 'withReply') {
    result = result.filter(review => review.reply)
  }
  
  // 应用排序
  if (sortValue.value === 'newest') {
    result.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
  } else if (sortValue.value === 'highest') {
    result.sort((a, b) => b.rating - a.rating)
  } else if (sortValue.value === 'lowest') {
    result.sort((a, b) => a.rating - b.rating)
  }
  
  return result
})

// 处理筛选变化
const handleFilterChange = () => {
  pagination.current = 1
}

// 处理排序变化
const handleSortChange = () => {
  pagination.current = 1
}

// 方法
const getRatingColor = (rating: number) => {
  const colors = {
    1: '#f5222d',
    2: '#fa8c16',
    3: '#faad14',
    4: '#52c41a',
    5: '#1890ff'
  }
  return colors[rating as keyof typeof colors] || '#1890ff'
}

// 获取随机头像
const getRandomAvatar = (id: number | string) => {
  const seed = id?.toString() || Math.random().toString()
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${seed}`
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '未知日期'
  
  try {
    // 尝试解析不同格式的日期
    let date: Date
    if (dateStr.includes('T')) {
      // ISO格式
      date = new Date(dateStr)
    } else if (dateStr.includes('-')) {
      // YYYY-MM-DD格式
      const parts = dateStr.split('-')
      date = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]))
    } else {
      // 时间戳格式
      date = new Date(parseInt(dateStr))
    }
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return dateStr
    }
    
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }).replace(/\//g, '-')
  } catch (e) {
    return dateStr
  }
}

// 预览图片
const previewImage = (url: string) => {
  if (!url) return
  
  // 获取当前评论的所有图片
  const currentReview = reviews.value.find(review => 
    review.photos && review.photos.includes(url)
  )
  
  if (currentReview && currentReview.photos && currentReview.photos.length > 0) {
    previewImages.value = currentReview.photos
    activePreviewIndex.value = currentReview.photos.indexOf(url)
    previewVisible.value = true
  } else {
    // 如果找不到相关评论，只预览当前图片
    previewImages.value = [url]
    activePreviewIndex.value = 0
    previewVisible.value = true
  }
}

// 加载酒店评论统计信息
const loadReviewStats = async () => {
  try {
    const response = await apiGetHotelReviewStats(props.hotelId) as any
    
    if (response.code === 200 && response.data) {
      reviewStats.totalReviews = response.data.totalReviews || 0
      reviewStats.averageRating = response.data.averageRating || 0
      reviewStats.ratingDistribution = response.data.ratingDistribution || {
        "5": 0,
        "4": 0,
        "3": 0,
        "2": 0,
        "1": 0
      }
      
      console.log('评论统计信息:', reviewStats)
    } else {
      message.error(response.msg || '获取评论统计信息失败')
    }
  } catch (error) {
    console.error('加载评论统计信息出错:', error)
    message.error('获取评论统计信息失败')
  }
}

const loadReviews = async (page = 1) => {
  try {
    loading.value = true
    const response = await apiGetHotelReviews(props.hotelId, page, pagination.pageSize) as unknown as ReviewResponse
    
    if (response.code === 200 && response.data) {
      const reviewData = response.data.records || []
      console.log('原始评论数据:', reviewData) // 调试用
      
      // 处理每条评论数据
      reviews.value = reviewData.map(review => {
        return {
          id: review.id,
          author: review.userName || '匿名用户',
          userName: review.userName,
          userAvatar: review.userAvatar,
          content: review.content,
          rating: review.rating,
          date: review.date || review.createTime || new Date().toISOString(),
          roomType: review.roomType || '标准房',
          photos: review.photos || [],
          tags: review.tags || [],
          reply: review.reply,
          replyDate: review.replyDate,
          status: review.status
        } as EnhancedHotelReview
      })
      
      console.log('处理后的评论数据:', reviews.value) // 调试用
      pagination.total = response.data.total || 0
    } else {
      message.error(response.msg || '获取评论失败')
    }
  } catch (error) {
    console.error('加载评论出错:', error)
    message.error('获取评论数据失败')
  } finally {
    loading.value = false
  }
}

// 直接跳转到订单页面
const goToOrderPage = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    message.warning('请先登录后再评论')
    router.push('/login')
    return
  }
  
  // 直接跳转到用户的订单页面
  router.push('/profile?tab=orders')
}

onMounted(() => {
  // 加载评论统计信息
  loadReviewStats()
  // 加载评论
  loadReviews()
})
</script>

<style scoped>
.hotel-reviews {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.section-icon {
  font-size: 24px;
  color: #1890ff;
}

h2 {
  font-size: 20px;
  margin: 0;
  color: #262626;
  font-weight: 600;
}

.review-summary {
  margin-bottom: 32px;
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.06);
  transition: all 0.3s ease;
}

.review-summary:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
  transform: translateY(-2px);
}

.rating-overview {
  display: grid;
  grid-template-columns: auto 1fr;
  gap: 48px;
  align-items: center;
}

.average-rating {
  text-align: center;
  padding-right: 48px;
  border-right: 1px solid #f0f0f0;
}

.rating-number {
  font-size: 48px;
  margin: 0;
  color: #1890ff;
  font-weight: 600;
}

.average-rating p {
  margin-top: 8px;
  color: #8c8c8c;
}

.rating-distribution {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.rating-bar {
  display: grid;
  grid-template-columns: 40px 1fr 40px;
  align-items: center;
  gap: 12px;
}

.filter-sort-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background-color: #f9f9f9;
  padding: 12px 16px;
  border-radius: 8px;
}

.filter-container, .sort-container {
  display: flex;
  align-items: center;
}

.filter-label, .sort-label {
  font-weight: 500;
  color: #595959;
  margin-right: 8px;
}

.add-review-section {
  margin-bottom: 24px;
  text-align: right;
}

.review-list {
  background: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.06);
}

.review-item {
  transition: all 0.3s ease;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  border: 1px solid #f0f0f0;
}

.review-item:hover {
  background: #f9f9f9;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.review-header {
  display: flex;
  align-items: center;
  gap: 16px;
}

.author-name {
  font-weight: 500;
  color: #262626;
}

.review-meta {
  color: #8c8c8c;
  font-size: 14px;
}

.review-tags {
  display: block;
  margin-top: 8px;
}

.hotel-reply {
  margin-top: 16px;
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 16px;
  position: relative;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.reply-icon {
  color: #faad14;
  margin-right: 8px;
  font-size: 16px;
}

.reply-title {
  font-weight: 500;
  color: #262626;
  margin-right: 12px;
}

.reply-time {
  font-size: 12px;
  color: #8c8c8c;
}

.reply-content {
  color: #595959;
  line-height: 1.6;
  white-space: pre-line;
}

.review-content {
  margin: 16px 0;
  color: #262626;
  line-height: 1.6;
  font-size: 15px;
  white-space: pre-line;
}

.review-images {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 16px;
}

.review-image-wrapper {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
}

.review-image-wrapper:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 10px rgba(0,0,0,0.15);
}

.review-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.empty-reviews {
  padding: 40px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .rating-overview {
    grid-template-columns: 1fr;
    gap: 24px;
  }
  
  .average-rating {
    padding-right: 0;
    border-right: none;
    padding-bottom: 24px;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .filter-sort-container {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .review-image-wrapper {
    width: 100px;
    height: 100px;
  }
}
</style> 